package com.aptemo.webetek.client.widgets.paging;

import java.util.ArrayList;
import java.util.List;

import com.aptemo.webetek.client.mvp.BasePresenter;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.HasWidgets;

public abstract class PagingController<TYPE> implements BasePresenter
{
	private int				step	= 5;
	private int				cursor	= 0;
	private PagingDisplay	mdisplay;

	private List<TYPE>		data;
	private Timer			timer	= new Timer()
									{

										@Override
										public void run()
										{
											mdisplay.update(cursor, step, data.size());
										}
									};

	public PagingController(PagingDisplay display, int step)
	{
		this.mdisplay = display;
		this.step = step;

		bind();
	}

	private void bind()
	{
		mdisplay.setVisible(false);

		mdisplay.getPagingNextHandler().addClickHandler(new ClickHandler()
		{

			@Override
			public void onClick(ClickEvent event)
			{
				cursor += step;

				updatePaging();
			}
		});

		mdisplay.getPagingPreviousHandler().addClickHandler(new ClickHandler()
		{

			@Override
			public void onClick(ClickEvent event)
			{
				cursor -= step;
				if (cursor < 0)
					cursor = 0;

				updatePaging();
			}
		});

		mdisplay.getPagingHomeHandler().addClickHandler(new ClickHandler()
		{

			@Override
			public void onClick(ClickEvent event)
			{
				cursor = 0;
				updatePaging();
			}
		});

//		mdisplay.getPagingEndHandler().addClickHandler(new ClickHandler()
//		{
//
//			@Override
//			public void onClick(ClickEvent event)
//			{
//				cursor = (data.size() / step) * step;
//				updatePaging();
//			}
//		});

	}

	public void setList(List<TYPE> data, int pageNo)
	{
		this.data = data;

		cursor = pageNo * step;

		updatePaging();
	}

	public List<TYPE> getPage(int index)
	{
		int size = data.size();
		List<TYPE> tmp = new ArrayList<TYPE>();
		for (int i = index * step; i < index * step + step; i++)
		{
			if (i >= size)
			{
				break;
			}
			tmp.add(data.get(i));
		}
		return tmp;
	}

	public List<TYPE> getCurrentPage()
	{
		int size = data.size();
		List<TYPE> tmp = new ArrayList<TYPE>();
		for (int i = cursor; i < cursor + step; i++)
		{
			if (i >= size)
			{
				break;
			}
			tmp.add(data.get(i));
		}
		return tmp;
	}

	public PagingDisplay getDisplay()
	{
		return mdisplay;
	}

	@Override
	public void go(HasWidgets container)
	{
		// container.clear();
		// container.add(mdisplay.getDisplay());
	}

	public void updatePaging()
	{
		List<TYPE> list = getCurrentPage();
		//
		refreshPaging(list);

		// timer.schedule(100);
		mdisplay.update(cursor, step, data.size());
	}

	public TYPE getItem(int index)
	{
		List<TYPE> list = getCurrentPage();
		return list.get(index);
	}

	public abstract void refreshPaging(List<TYPE> data);

}
